<script setup>
import PluginsInstall from '@/core/Frame/Install/PluginsInstall'
import config from '@/core/Frame/Config/MenuConfig'
import { ref, inject, onUnmounted, watch } from 'vue'

const getViewerInstance = inject('getViewerInstance')
const getWidgetsManager = inject('getWidgetsManager')
const EarthOnLoad = inject('earthOnLoad')

let viewer = null
let widgetsManager = getWidgetsManager()

// 安装插件
let plugins = PluginsInstall()

// 监听地球状态
watch(EarthOnLoad, (val) => {
    if (!val) return

    viewer = getViewerInstance()

    // 插件初始化
    for (let key in plugins) {
        plugins[key].register(viewer, widgetsManager)
    }
})

// 当前组件销毁完毕回调函数
onUnmounted(() => {
    // 销毁插件
    for (let key in plugins) {
        plugins[key].destroy()
    }
    plugins = {}
    viewer = null
    widgetsManager = null
})


const menuCfg = ref(config)

// 刷新所有Items的可用状态
const refreshItemsEnable = () => {
    for (let i = 0; i < menuCfg.value.length; i++) {
        let item = menuCfg.value[i]
        const isEnable = plugins[item.lib].commands[item.command].isEnable()
        item.disabled = isEnable ? false : true
    }
}

// 定义菜单按钮的todo方法
const todo = ($event, item) => {
    // e.target.checked
    if (item.disabled) return
    plugins[item.lib].commands[item.command].execute(item.paramter)

    refreshItemsEnable()
}
</script>

<template>
    <div class="btn-group">
        <div v-for="item in menuCfg" :key="item.name">
            <div v-if="item.type === 'item'" class="btn" :class="item.disabled ? 'disabled' : ''"
                @click="todo($event, item)">
                {{ item.name }}
            </div>
            <div v-else-if="item.type === 'checkbox'">
                <label><input name="Fruit" type="checkbox" value="123" @change="todo($event, item)" />
                    {{ item.name }}
                </label>
            </div>
        </div>
    </div>
</template>

<style scoped lang="less">
.btn-group {
    height: 100%;
    display: flex;
    align-items: center;
    background: linear-gradient(180deg, white, #eaeaea);

    .btn {
        border: 1px solid transparent;
        padding: 5px;
        margin: 5px;
        border-radius: 2px;
        user-select: none;

        &:hover:not(.disabled) {
            cursor: pointer;
            border: 1px solid #F1C43F;
            background: #fdeeb3;
        }

        &.disabled {
            cursor: default;
            color: #888;
        }
    }
}
</style>